package com.gitee.wsl.data.source

import arrow.atomic.Atomic
import arrow.atomic.update
import kotlin.coroutines.cancellation.CancellationException

interface AutoCloseScope {
     fun onClose(release: (Throwable?) -> Unit)

     fun <A> autoClose(
        acquire: () -> A,
        release: (A, Throwable?) -> Unit
    ): A = acquire().also { a -> onClose { release(a, it) } }

     fun <A : AutoCloseable> install(autoCloseable: A): A =
        autoCloseable.also { onClose { autoCloseable.close() } }
}

//
//@PublishedApi
//internal class DefaultAutoCloseScope : AutoCloseScope {
//    private val finalizers = Atomic(emptyList<(Throwable?) -> Unit>())
//
//    override fun onClose(release: (Throwable?) -> Unit) {
//        finalizers.update { it + release }
//    }
//
//    fun close(error: Throwable?): Nothing? {
//        return finalizers.getAndSet(emptyList()).asReversed().fold(error) { acc, finalizer ->
//            acc.add(runCatching { finalizer(error) }.exceptionOrNull())
//        }?.let { throw it }
//    }
//
//    private fun Throwable?.add(other: Throwable?): Throwable? {
//        if (other !is CancellationException) other?.throwIfFatal()
//        return this?.apply {
//            other?.let { addSuppressed(it) }
//        } ?: other
//    }
//}
